<template>
  <div class="about-container">
    <el-header>基本信息</el-header>
    <el-main>
      <!-- 展示头像部分 -->
      <div class="demo-image__preview about-img">
        <!-- 按需展示头像 -->
          <el-image
            class="img"
            :src="userInfo.userPic"
            v-if="progressFlag&&userInfo.userPic!==undefined"
            :lazy="true"
            :preview-src-list="srcList"
            title="点击查看大图">
             <div slot="placeholder" class="loding"  v-loading="loading"
              element-loading-text="拼命加载中">
         </div>
              <!-- 若加载失败 -->
              <el-button slot="error" class="loderr" @click="refreshImg">请刷新重试</el-button>
          </el-image>
          <!-- 文字头像 -->
          <span
            class="text-avatar"
            v-if="!progressFlag"
            >{{avaentText}}
          </span>
        </div>

      <div class="cropper-app">
        <el-upload action="#"
          class="btn"
          drag
          :auto-upload="true"
          :show-file-list="false"
          :on-change="handleCrop"
          :before-upload="beforeAvatarUpload"
        >
        <el-button type="success" plain round class="img-btn" v-if="!loadingtext"  size="mini">更新头像</el-button>
        <el-button type="success" v-if="loadingtext" disabled round class="img-load" size="mini" :loading="loadingtext">上传中...</el-button>
        </el-upload>

    <!-- 剪裁组件弹窗 -->
    <cropperImage
      :dialogVisible="showCropper"
      :cropper-option="cropperOption"
      :file-size="fileSize"
      :cropper-style="cropperStyle"
      @close="showCropper=false"
      @uploadCropper="uploadImg"
    />
  </div>
      <!-- 基本信息提交表单 -->
      <el-form
        ref="form"
        :model="userInfo"
        :rules="rules"
        label-width="40px"
      >
        <el-form-item prop="nickname" class="name-title">
          <span v-if="!inputVisible">{{ userInfo.nickname }}</span>
          <el-input
            v-if="inputVisible"
            ref="iptRef"
            v-model="userInfo.nickname"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <span  v-if="!inputVisible">{{ userInfo.gender }}</span>
          <el-radio-group v-if="inputVisible" v-model="userInfo.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item class="about-btn">
            <el-button
            @click="ModifyInfo"
            title="点击修改个人信息"
            v-if="!inputVisible"
            plain
            size="medium"
          >修改信息</el-button>
            <el-button v-if="inputVisible" @click="Update('form')" type="success" plain>更新</el-button>
          <el-button v-if="inputVisible" size="medium" @click="CancelUpdate('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </div>
</template>

<script>
import { person, updatUser, updatImg } from '@/utils/api/mine/perCenter.js'
import cropperImage from "@/views/pageIn/mine/components/Copper.vue"
export default {
  inject: ["reload"],
  name: 'AboutMe',
  props: {},
  components: {
    cropperImage
  },
  created () {
    // 获取用户信息
    this.getInfo()
  },
  data () {
    // 修改信息时的验证规则
    var validUsername = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
      if (!value.match(reg)) {
        callback(
          new Error(
            "用户名要求数字字母的组合"
          )
        )
      } else {
        callback()
      }
    }
    return {
      cropperData: {},
      showCropper: false, // 显示裁剪弹窗
      canCropper: false,
      fileSize: 2, // 限制文件上传大小
      cropperOption: {
        img: '',
        autoCropWidth: 200,
        autoCropHeight: 200
      },
      cropperStyle: {
        width: '600px',
        height: '300px'
      },
      inputVisible: false, // 修改个人按钮是否展示
      progressFlag: true, // 头像按需展示
      loadingtext: false,
      // 验证规则
      rules: {
        nickname: [
          { required: true, message: '请输入用户名', trigger: "blur" },
          { min: 1, max: 5, message: '长度在1-5个字符', trigger: "blur" },
          { validator: validUsername, trigger: "blur" }
        ]
      },
      userInfo: {
      },
      // 图片预览设置
      srcList: [],
      // 修改信息前，备份用户数据
      oldName: '',
      oldSex: '',
      // 初始化文字头像内容
      avaentText: '',
      loading: true,
    }
  },
  methods: {
    // 获取用户信息
    getInfo () {
      // 获取全部基本信息
      person().then(res => {
        if (res.status === 200) {
          this.userInfo = res.data.data
          this.srcList.push(this.userInfo.userPic)
          // 判断性别并保存
          if (this.userInfo.gender) {
            this.userInfo.gender = '男'
          } else {
            this.userInfo.gender = '女'
          }
          this.IsAvaent()
        } else {
          this.$message({
            type: 'waring',
            message: '用户信息获取失败，请刷新重试！'
          })
        }
      })
    },
    // 判断是否有头像,若无展示文字头像
    IsAvaent () {
      if (this.userInfo.userPic === null) {
        this.progressFlag = false
        var textName = this.userInfo.nickname || this.userInfo.username
        this.avaentText = textName.slice(-2).toUpperCase()
      } else { this.progressFlag = true }
    },
    // 展示修改信息
    ModifyInfo () {
      if (this.inputVisible) return
      // 保存修改前的信息
      this.oldName = this.userInfo.nickname;
      this.oldSex = this.userInfo.gender;
      this.oldImg = this.userInfo.url;
      // 展示修改信息
      this.inputVisible = !this.inputVisible
    },
    // 取消修改
    CancelUpdate (formName) {
      if (!this.inputVisible) return
      // 清空错误信息
      this.$refs[formName].resetFields();
      // 渲染修改前信息
      this.userInfo.nickname = this.oldName;
      this.userInfo.gender = this.oldSex;
      this.userInfo.url = this.oldImg;
      this.inputVisible = !this.inputVisible
    },
    // 确认更新信息
    Update (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.UpdatUser()
          location.reload()
          this.IsAvaent()
          this.inputVisible = !this.inputVisible
        } else {
          return false;
        }
      });
    },
    // 更新信息
    UpdatUser () {
      updatUser(this.userInfo).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '更新成功！'
          })
        } else {
          this.$message({
            type: 'waring',
            message: '更新失败！'
          })
        }
      })
    },
    refreshImg () {
      this.reload()
    },
    // 点击弹出剪裁框
    handleCrop (file) {
      this.$nextTick(() => {
        if (this.canCropper) {
          this.cropperOption.img = window.URL.createObjectURL(file.raw)
          this.showCropper = this.canCropper
        }
      })
    },
    // 上传前校验
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2 MB!')
      }
      // 校验通过后显示裁剪框
      this.canCropper = isJPG && isLt2M
      return false
    },

    // 自定义的提交事件
    uploadImg (f, data) {
      this.progressFlag = true
      const formdata = new FormData()
      formdata.append('pic', f)
      this.loadingtext = true;
      this.cropperData.iconUrl = data
      this.showCropper = false
      updatImg(formdata)
        .then(() => {
          this.loadingtext = false;
          this.$notify({
            title: '成功',
            message: '更换头像成功',
            type: 'success',
            position: 'top-left'
          })
          location.reload()
        }).then(() => {
          this.loadingtext = false;
        })
    },
  }
}

</script>

<style lang="less" scoped>
.about-container {
  margin-top: 20px;
  position: relative;
  margin-right: 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  min-height: 250px;
  -moz-box-shadow: 2px 2px 10px #909090;/*firefox*/
    -webkit-box-shadow: 2px 2px 10px #909090;/*safari或chrome*/
    box-shadow:2px 2px 10px #909090;/*opera或ie9*/
  .el-header {
    height: 40px !important;
    line-height: 40px;
    border-bottom: 1px solid #ddd;
    background-color: #fafafa;
  }
  /deep/.el-form-item__content{
    margin-left: 0 !important;
    font-size: 16px;
  }
  .name-title {
    text-align: center;
  }
  .about-img {
    text-align: center;
    .img {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      box-shadow: 0 0 40px gainsboro;
    }
    .text-avatar{
       cursor: default;
       display: inline-block;
       width: 100px;
       height: 100px;
       background-color:orange;
       line-height: 100px;
       font-size: 40px;
       color: rgb(255, 255, 255);
       position: relative;
       border-radius: 50%;
     }
  }
  /deep/.el-form-item {
    margin-bottom: 10px;
  }
  .el-input {
    height: 30px;
    width: 70%;
  }
  .about-btn{
    text-align: center;
    margin-top: 30px;
  }

  .btn{
    margin-top: 10px;
    text-align: center;
    .img-load{
     opacity: 1;
     cursor:none;
    }
    .img-btn{
      opacity: .3;
    }
    .img-btn:hover{
      opacity: 1;
      transition: 1.5s;
    }
}

  .loderr{
    height: 100%;
    text-align: center;
    color: #aaa;
  }
   .loding{
    margin-top: -10px;
      width: 100px;
      height: 100px;
  }
}
.cropper-app  {
    /deep/ .el-dialog{
    width: max-content;
    max-width: 860px;
    height: 520px;
    }
    /deep/ .el-image__inner {
      overflow: hidden;
      border-radius: 6px;
    }
  }

.cropper-app /deep/ .el-upload-dragger {
  border: 0;
  height: auto;
  width: auto;
}
.upload-box {
  height: 100%;
  background: #ecedf2;
}
.el-upload-tips {
  margin-top: 10px;
  font-size: 14px;
  color: #a7aebb;
}
.select-btn {
  margin-top: 50px;
}

</style>
